package com.temp.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.temp.enumeration.EmailType;
import com.temp.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.mail.internet.InternetAddress;
import java.io.File;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class EmailService {
    @Autowired
    private JavaMailSender javaMailSender;//注入邮件工具类

    @Value("${spring.mail.username}")
    private String fromEmail;

    public void send(String name, String to, String subject, String content, Boolean isHtml, String cc, String bcc, List<File> files) {

        if (StringUtils.isEmpty(fromEmail)
                || StringUtils.isEmpty(to)
                || StringUtils.isEmpty(subject)
                || StringUtils.isEmpty(content)) {
            throw new BaseException("apiMsg.emailNotThree");
        }
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            messageHelper.setFrom(new InternetAddress(name + "<" + fromEmail + ">"));
            messageHelper.setTo(to.split(","));
            messageHelper.setSubject(subject);
            messageHelper.setText(content, isHtml);
            //抄送
            if (!StringUtils.isEmpty(cc)) {
                messageHelper.setCc(cc.split(","));
            }
            //密送
            if (!StringUtils.isEmpty(bcc)) {
                messageHelper.setCc(bcc.split(","));
            }
            //添加邮件附件
            if (!CollectionUtils.isEmpty(files)) {
                for (File file : files) {
                    messageHelper.addAttachment(file.getName(), file);
                }
            }
            // 邮件发送时间
            messageHelper.setSentDate(new Date());
            //正式发送邮件
            javaMailSender.send(messageHelper.getMimeMessage());
        } catch (Exception e) {
            log.info("邮件发送失败".concat(e.getMessage()));
            throw new BaseException("apiMsg.sendError");
        }
    }

    public void sendText(String name, String to, String subject, String content) {
        this.send(name, to, subject, content, false, null, null, null);
    }

    public void sendHtml(String name, String to, String subject, String content) {
        this.send(name, to, subject, content, true, null, null, null);
    }
}

